package com.aida.evil.eda.Login;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.dd.CircularProgressButton;
import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;


/****************************************************
 * Register
 * 作者：白雨濃  evil
 * 时间：16-2-9 21:47
 * 邮箱：evilbai@foxmail.com
 * 页面用途：注册界面
 ****************************************************/
public class Register extends AppCompatActivity
{
    private static final String REGISTERURL = "http://" + NetworkData.ServiceIP + "/Register";

    private EditText userName_EditText, password_EditText, repassword_EditText;
    private CircularProgressButton submit_Button;/*注册提交按钮*/
    private Button intent_Button;/*跳转到手机验证界面*/

    private String username, password, repassword;/*用户名，密码，重复密码*/
    private String country, phone;/*国家，手机号*/

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        SMSSDK.initSDK(this, "1177dd9f6b3e0", "4509651f324181882bdfb43445921ec5");

        /*动态加载背景图片，以免耗用ui线程时间*/
        Picasso.with(this).load(R.mipmap.login_background)
                .into((ImageView) findViewById(R.id.register_background));

        findViewByID();
        {
            submit_Button.setIndeterminateProgressMode(true);
        }

        getPermissions();/*获取权限 android 6.0情况下*/

        onClick();/*点击事件*/

    }


    /**
     * 查找控件
     */
    private void findViewByID()
    {
        userName_EditText = (EditText) findViewById(R.id.register_userName);
        password_EditText = (EditText) findViewById(R.id.register_password);
        repassword_EditText = (EditText) findViewById(R.id.register_repassword);
        submit_Button = (CircularProgressButton) findViewById(R.id.register_submit);
        intent_Button = (Button) findViewById(R.id.register_intent);
    }

    /**
     * 获得输入框中的内容
     */
    public void getEditTextString()
    {
        username = userName_EditText.getText().toString();
        password = Encrypt_MD5.GetMD5Code(password_EditText.getText().toString());
        repassword = Encrypt_MD5.GetMD5Code(repassword_EditText.getText().toString());
    }

    /**
     * 点击事件
     */
    private void onClick()
    {
        intent_Button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                intentToSMSSDK();
            }
        });

        submit_Button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                getEditTextString();/*获得输入框中的内容*/

                if (password_EditText.getText().toString()
                        .equals(repassword_EditText.getText().toString()))
                {
                    if (password_EditText.getText().length() > 5)
                    {
                        if (submit_Button.getProgress() == -1 || submit_Button.getProgress() == 100)
                        {
                            submit_Button.setProgress(0);
                        }
                        else
                        {
                            submit_Button.setProgress(50);
                            toNetWork();
                        }
                    }
                    else
                    {
                        CustomSuperActivityToast.makeText(Register.this, "密码长度过短", "确认").show();
                    }
                }
                else
                {
                    CustomSuperActivityToast.makeText(Register.this, "两次密码输入不一致！", "确定").show();
                }
            }
        });

    }

    /**
     * 网络通信
     */
    private void toNetWork()
    {
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            CustomSuperActivityToast superActivityToast_red = CustomSuperActivityToast.makeText(Register.this);
            CustomSuperActivityToast superActivityToast = CustomSuperActivityToast.makeText(Register.this, "注册成功", "返回登陆");

            @Override
            public void reqSuccess(String response)
            {
                Log.i("返回", "" + response);
                /*注册成功*/
                if (response.equals("1"))
                {
                    submit_Button.setProgress(100);
                    intent_Button.setBackgroundColor(getResources().getColor(R.color.alphagreen));
                    superActivityToast.setDuration(Integer.MAX_VALUE);
                    submit_Button.setClickable(false);
                    superActivityToast.setButtonOnclik(new SuperToast.OnClickListener()
                    {
                        @Override
                        public void onClick(View view, Parcelable token)
                        {
                            finish();
                        }
                    });
                    superActivityToast.show();
                }
                /*该手机号已经注册*/
                else if (response.equals("ERROR_PRIMARY"))
                {
                    intent_Button.setVisibility(View.VISIBLE);
                    submit_Button.setVisibility(View.GONE);
                    superActivityToast_red.setText("该手机号已经注册");
                    superActivityToast_red.setBackground(SuperToast.Background.RED);
                    superActivityToast_red.setButtonText("确定");
                    superActivityToast_red.show();
                }
                /*注册失败*/
                else if (response.equals("ERROR:PHONE_NOTIN_HANDAN"))
                {
                    submit_Button.setProgress(-1);
                    superActivityToast_red.setText("您的手机号所在地不是邯郸，请使用邯郸本地的手机号注册！");
                    superActivityToast_red.setBackground(SuperToast.Background.RED);
                    superActivityToast_red.setButtonText("确定");
                    superActivityToast_red.show();
                }
                /*未知错误*/
                else
                {
                    submit_Button.setProgress(-1);
                    superActivityToast_red.setText("未知错误");
                    superActivityToast_red.setBackground(SuperToast.Background.RED);
                    superActivityToast_red.setButtonText("确定");
                    superActivityToast_red.show();
                }

            }


            @Override
            public void reqError(String error)
            {
                superActivityToast_red.setText("网络错误");
                superActivityToast_red.setBackground(SuperToast.Background.RED);
                superActivityToast_red.setButtonText("确定");
                superActivityToast_red.show();
            }
        };
        Map<String, String> map = new HashMap<>();
        map.put("phoneNum", phone);
        //map.put("phoneNum", "18832030508");
        map.put("userIMEI", UserData.DATA_IMEI);
        map.put("username", username);
        map.put("password", password);
        VolleyHttpRequest.String_request(REGISTERURL, map, stringVolleyHandler);

        UserData.DATA_PHONENUM = phone;
    }

    /**
     * 获取权限
     * android 6.0情况下
     */
    private void getPermissions()
    {
        if (Build.VERSION.SDK_INT >= 23)
        {
            int readPhone = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            int readSms = checkSelfPermission(Manifest.permission.READ_SMS);
            int readContacts = checkSelfPermission(Manifest.permission.READ_CONTACTS);
            int readSdcard = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);

            int requestCode = 0;
            ArrayList<String> permissions = new ArrayList<String>();
            if (readPhone != PackageManager.PERMISSION_GRANTED)
            {
                requestCode |= 1 << 0;
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (readSms != PackageManager.PERMISSION_GRANTED)
            {
                requestCode |= 1 << 1;
                permissions.add(Manifest.permission.READ_SMS);
            }
            if (readContacts != PackageManager.PERMISSION_GRANTED)
            {
                requestCode |= 1 << 2;
                permissions.add(Manifest.permission.READ_CONTACTS);
            }
            if (readSdcard != PackageManager.PERMISSION_GRANTED)
            {
                requestCode |= 1 << 3;
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (requestCode > 0)
            {
                String[] permission = new String[permissions.size()];
                this.requestPermissions(permissions.toArray(permission), requestCode);
                return;
            }
        }
    }

    /**
     * 跳转到短息验证界面
     * <p/>
     * ！！！验证手机号是否已经注册！！！
     */
    private void intentToSMSSDK()
    {
        //打开注册页面
        RegisterPage registerPage = new RegisterPage();
        registerPage.setRegisterCallback(new EventHandler()
        {
            public void afterEvent(int event, int result, Object data)
            {
                // 解析注册结果
                /*注册成功*/
                if (result == SMSSDK.RESULT_COMPLETE)
                {
                    intent_Button.setVisibility(View.GONE);
                    submit_Button.setVisibility(View.VISIBLE);
                    @SuppressWarnings("unchecked")
                    HashMap<String, Object> phoneMap = (HashMap<String, Object>) data;
                    country = (String) phoneMap.get("country");
                    phone = (String) phoneMap.get("phone");
                    // 提交用户信息
                    registerUser(country, phone);
                }
                /*注册失败*/
                if (result == SMSSDK.RESULT_ERROR)
                {
                    CustomSuperActivityToast.makeText(Register.this, "手机验证失败", "确认")
                            .setBackground(SuperToast.Background.RED).show();
                }
            }
        });
        registerPage.show(Register.this);
    }

    /**
     * 短信注册
     *
     * @param country 国家
     * @param phone   手机号
     */
    private void registerUser(String country, String phone)
    {
        Random rnd = new Random();
        int id = Math.abs(rnd.nextInt());
        String uid = String.valueOf(id);
        //String avatar = AVATARS[id % 12];
        //String nickName = "Eda_User_" + uid;
        String nickName = UserData.DATA_USERNAME;
        SMSSDK.submitUserInfo(uid, nickName, null, country, phone);
    }


}
